import React from 'react';
import { Link } from 'react-router';
import { Button, Steps, Form, Input, Row, Col, message } from 'antd';
import { _validate, sendSms, checkSms, smsResetPass } from '../../store/actions';
import { connect } from 'react-redux';
import classNames from 'classnames';

const createForm = Form.create,
    FormItem = Form.Item,
    Step = Steps.Step;
import FormRegister from '../../components/formRegister';
import Header from '../../components/header';

class _SendSms extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            sendTxt:'发送短信验证码',
            sendStyle:'primary',
            sendable:false
        }
    }
    sendSms(e){
        const _this = this;
        _validate(e,_this,function(data){
            let i = 60;
            _this.props.dispatch(sendSms(data.mobile,function(){
                message.success('正在请求发送验证码短信',2);
                _this.props.afterSend(data.mobile)
            },function(){
                message.warning('业务处理失败',1)
            },function(e){
                message.error('error请求失败',1)
            }));
            const s = setInterval(function(){
                if(i>0){
                    _this.setState({
                        sendStyle:'',
                        sendable:true,
                        sendTxt:`${i--} 秒后可以重发`
                    });
                }else{
                    _this.setState({
                        sendTxt:`发送短信验证码`,
                        sendStyle:'primary',
                        sendable:false
                    },function(){
                        clearInterval(s)
                    });
                }
            },1000)
        })
    }

    checkMob(rule, value, callback){
        const _reg = /^1[3|4|5|7|8]\d{9}$/,
            result = _reg.test(value);
        if (!result && value) {
            callback('请输入正确格式的手机号')
        } else {
            callback();
        }
    }
    render(){
        const { getFieldProps } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 7 },
            wrapperCol: { span: 12 }
        };
        const mobileProps = getFieldProps('mobile', {
            validate: [{
                rules: [
                    { required: true,message: '请输入您的账号绑定的手机号' },
                    { validator: this.checkMob.bind(this) }
                ],
                trigger: 'onBlur'
            }],
        });
        return (
            <Form horizontal form={this.props.form} >
                <FormItem
                    {...formItemLayout}
                    label="手机号"
                >
                    <Input disabled={this.state.sendable} {...mobileProps} placeholder="请输入注册时绑定的手机号" style={{ width: '60%', marginRight: 8 }} />
                    <Button disabled={this.state.sendable} type={this.state.sendStyle} onClick={this.sendSms.bind(this)}>{this.state.sendTxt}</Button>
                </FormItem>
            </Form>
        )
    }
}
const SendSms = createForm()(_SendSms);

class _SubmitCode extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            active:false
        }
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    handleSubmit(e) {
        e.preventDefault();
        const _this = this;
        _validate(e,_this,function(code){
            _this.setState({
                active: true
            });
            const opts = {
                mobile:_this.state.mobile,
                smscode:code.code
            };
            _this.props.dispatch(checkSms(opts,function(){
                message.success('短信验证成功，请设置密码！');

                _this.props.readyForReset(opts);
                _this.props.goStep(1)
            },function(res){
                message.error(res.head.msg);
                _this.props.form.resetFields();
                _this.setState({
                    active: false
                })
            },function(){
                message.error('请求出错了.....',1);
                _this.setState({
                    active: false
                })
            }))
        });
    }
    handleBack(e){
        e.preventDefault();
        this.context.router.push('/login')
    }
    getMobile(m){
        this.setState({
            mobile: m
        })
    }
    render(){
        const { getFieldProps } = this.props.form;
        const formItemLayout = {
            labelCol: { span: 7 },
            wrapperCol: { span: 12 }
        };
        const codeProps = getFieldProps('code', {
            validate: [{
                rules: [
                    { required: true,message: '请输入短信验证码' }
                ],
                trigger: 'onBlur'
            }],
        });
        return (
            <div>
                <SendSms dispatch={this.props.dispatch} afterSend={this.getMobile.bind(this)} />
                <Form horizontal form={this.props.form} >
                    <FormItem
                        {...formItemLayout}
                        label="验证码"
                    >
                        <Input {...codeProps} />
                    </FormItem>
                    <FormItem wrapperCol={{ span: 12, offset: 7 }}>
                        <Button type="primary" disabled={this.state.active} onClick={this.handleSubmit.bind(this)}>下一步</Button>
                        &nbsp;&nbsp;&nbsp;&nbsp;
                        <Button type="ghost" onClick={this.handleBack.bind(this)}>返回登录</Button>
                    </FormItem>
                </Form>
            </div>
        )
    }
}
const SubmitCode = createForm()(_SubmitCode);

/*class SendFeed extends React.Component{
    render(){
        const _reg = /^\w*@/,
            _n = this.props.email.replace(_reg,'mail.');
        function checkMail(){
            window.location.href = 'http://'+_n
        }
        return (
            <div style={{
                    textAlign: 'center'
                }}>
                <h2 style={{
                    fontSize: '16px',
                    color: '#999',
                    fontWeight: 'normal',
                    marginBottom: '20px'
                }}>我们已经向 <b style={{color:"#f00"}}>{this.props.email}</b> 发送了邮件，其中包含重置密码的链接，15分钟后链接失效</h2>
                <Button type='primary' onClick={checkMail}>去查看邮件</Button>
            </div>
        )
    }
}*/
class _ResetPass extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            passBarShow: false, // 是否显示密码强度提示条
            rePassBarShow: false,
            passStrength: 'L', // 密码强度
            rePassStrength: 'L'
        };
        this.getPassStrenth = this.getPassStrenth.bind(this);
        this.renderPassStrengthBar = this.renderPassStrengthBar.bind(this);
        this.checkPass = this.checkPass.bind(this);
        this.checkPass2 = this.checkPass2.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.resetFields = this.resetFields.bind(this);
    }
    getPassStrenth(value, type) {
        if (value) {
            let strength;
            // 密码强度的校验规则自定义，这里只是做个简单的示例
            if (value.length < 6) {
                strength = 'L';
            } else if (value.length <= 9) {
                strength = 'M';
            } else {
                strength = 'H';
            }
            if (type === 'password') {
                this.setState({ passBarShow: true, passStrength: strength });
            } else {
                this.setState({ rePassBarShow: true, rePassStrength: strength });
            }
        } else {
            if (type === 'pass') {
                this.setState({ passBarShow: false });
            } else {
                this.setState({ rePassBarShow: false });
            }
        }
    }
    checkPass(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrenth(value, 'password');
        if (form.getFieldValue('password')) {
            form.validateFields(['rePass'], { force: true });
        }
        callback();
    }
    checkPass2(rule, value, callback) {
        const form = this.props.form;
        this.getPassStrenth(value, 'rePass');

        if (value && value !== form.getFieldValue('password')) {
            callback('两次输入密码不一致！');
        } else {
            callback();
        }
    }
    renderPassStrengthBar(type) {
        const strength = type === 'password' ? this.state.passStrength : this.state.rePassStrength;
        const classSet = classNames({
            'ant-pwd-strength': true,
            'ant-pwd-strength-low': strength === 'L',
            'ant-pwd-strength-medium': strength === 'M',
            'ant-pwd-strength-high': strength === 'H'
        });
        const level = {
            L: '低',
            M: '中',
            H: '高'
        };
        return (
            <div>
                <ul className={classSet}>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-1"> </li>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-2"> </li>
                    <li className="ant-pwd-strength-item ant-pwd-strength-item-3"> </li>
                    <span className="ant-form-text">
                        {level[strength]}
                    </span>
                </ul>
            </div>
        );
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    handleSubmit(e) {
        const _this = this;
        _validate(e,_this,function(values){
            if(!_this.props.mobile){
                message.error("请重新获取短信验证码，请不要刷新页面",1);
                _this.props.goStep(0);
                return
            }
            const sendData = {
                mobile:_this.props.mobile,
                smscode:_this.props.smscode,
                username:values.username,
                password:values.password
            };
            _this.props.dispatch(smsResetPass(sendData,function(){
                message.success('修改密码成功，请牢记新密码',1);
                _this.context.router.push('/login');
                return;
            },function(res){
                message.error(res.head.msg+"，请重新提交新密码和用户名",1);
                return;
            }))
        });
    }
    resetFields(){
        this.props.form.resetFields();
        this.setState({
            passBarShow: false,
            rePassBarShow: false
        })
    }
    checkUserName(rule, value, callback){
        const _reg = /^[a-zA-Z\d]\w{4,18}[a-zA-Z\d]$/;
        const _regEmail = /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/;
        const result = _reg.test(value);
        const result2 = _regEmail.test(value);
        if (!result && !result2) {
            callback('请输入您要重置密码的账号')
        } else {
            callback();
        }
    }
    render(){
        const formItemLayout = {
            labelCol: { span: 6 },
            wrapperCol: { span: 18 }
        };
        const { getFieldProps } = this.props.form;
        const usernameProps = getFieldProps('username', {
            rules: [
                { required: true, message: '必填项' },
                { validator: this.checkUserName }
            ],
            validateTrigger:'onBlur'
        });
        const passProps = getFieldProps('password', {
            rules: [
                { required: true, min:6,max:20,whitespace: true,message: '密码为6-20位' },
                { validator: this.checkPass }
            ]
        });
        const rePassProps = getFieldProps('rePass', {
            rules: [{
                required: true,
                whitespace: true,
                message: '请再次输入密码'
            }, {
                validator: this.checkPass2
            }]
        });
        return (
            <div>
                <Form horizontal form={this.props.form}>
                    <Row>
                        <Col span="18">
                            <FormItem
                                {...formItemLayout}
                                label="用户名"
                            >
                                <Input{...usernameProps}  type="text" placeholder="请输入您的用户名" id="username" />
                            </FormItem>
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">
                            <FormItem
                                {...formItemLayout}
                                label="新密码"
                            >
                                <Input {...passProps} type="password"
                                                      onContextMenu={false} onPaste={false} onCopy={false} onCut={false}
                                                      autoComplete="off" id="password"
                                />
                            </FormItem>
                            <FormItem
                                {...formItemLayout}
                                label="确认新密码"
                            >
                                <Input {...rePassProps} type="password"
                                                        onContextMenu={false} onPaste={false} onCopy={false} onCut={false}
                                                        autoComplete="off" id="rePass"
                                />
                            </FormItem>
                        </Col>
                        <Col span="6">
                            {this.state.passBarShow ? this.renderPassStrengthBar('pass') : null}
                        </Col>
                    </Row>
                    <Row>
                        <Col span="18">
                            <Col span="18" offset="6">
                                <Button type="primary" onClick={this.handleSubmit}>修改密码</Button>
                                &nbsp;&nbsp;&nbsp;&nbsp;
                                <Button onClick={this.resetFields}>重置</Button>
                            </Col>
                        </Col>
                    </Row>
                </Form>
            </div>
        )
    }
}
const ResetPass = createForm()(_ResetPass);
class __FormSmsResetPass extends React.Component{
    constructor(props){
        super(props);
        this.state = {
            current:parseInt(this.props.query.step) || 0,
            opts:{}
        }
    };
    static contextTypes = {
        router: React.PropTypes.object
    };
    goStep(n){
        this.setState({
            current:n
        })
    };
    readyForReset(o){
        this.setState({
            opts: o
        })
    };
    renderContent(step){
        switch(step){
            case 0:
                return (
                    <SubmitCode
                        dispatch={this.props.dispatch}
                        goStep={this.goStep.bind(this)}
                        readyForReset={this.readyForReset.bind(this)} />
                );
            case 1:
                return (
                    <div>
                        <ResetPass
                            mobile = {this.state.opts.mobile}
                            smscode = {this.state.opts.smscode}
                            dispatch = {this.props.dispatch}
                            goStep={this.goStep.bind(this)}
                        />
                    </div>
                );
            default:
                return ('....')
        }
    }
    render(){
        return (
            <div>
                <h2 id="accessFormTitle">通过短信重置密码</h2>
                <div style={{
                    padding:'10px 40px'
                }}>
                    <Steps current={this.state.current}>
                        <Step title="获取短信验证码" />
                        <Step title="重置密码" />
                        <Step title="成功" />
                    </Steps>
                    <div style={{
                        padding: '40px 0 20px'
                    }}>
                        {this.renderContent(this.state.current)}
                    </div>
                    <Link to="/mail-reset-pass">我要使用 <b>email</b> 找回密码</Link>
                </div>
            </div>
        )
    }
}

const _FormSmsResetPass = connect((state)=>{
    const { query } = state.routing.locationBeforeTransitions;
    return { query }
})(__FormSmsResetPass);

export default class SmsResetPass extends React.Component{
    constructor(props){
        super(props)
    }
    static contextTypes = {
        router: React.PropTypes.object
    };
    render(){
        return(
            <Row>
                <Col  xs={{span:24}}
                      sm={{span:24}}
                      md={{span:20,offset:2}}
                      lg={{span:16,offset:4}}
                     style={{
                        marginTop:'20px',
                        padding:'0 0 20px',
                        marginBottom:'20px',
                        backgroundColor:'#fff'}}
                    >
                    <_FormSmsResetPass />
                </Col>
            </Row>
        )
    }
}